/***************************************************************************
 *            callbacks.c
 *
 *  Sun Aug 13 13:03:57 2006
 *  Copyright  2006  Alexander P Telenga
 *  telenga@gmail.com
 ****************************************************************************/

/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */
#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

#include <gtk/gtk.h>
#include <gdk/gdk.h>
#include "callbacks.h"
#include "interface.h"
#include "support.h"
#include "include/rtf_parser.h"
#include "include/var.h"
#include "include/fb2parser.h"

gchar *file_name = NULL;
int workfile = -1;

void
on_open_activate (GtkMenuItem * menuitem, gpointer user_data)
{
	GtkWidget *OpenDialog;

	OpenDialog = create_easyreader_fileopen ();
	gtk_widget_show (OpenDialog);
}


void
on_quit_activate (GtkMenuItem * menuitem, gpointer user_data)
{
	gtk_main_quit ();
}


void
on_copy_activate (GtkMenuItem * menuitem, gpointer user_data)
{
	GtkTextBuffer *textbuffer = NULL;

	g_assert (GTK_IS_TEXT_VIEW (user_data));
	textbuffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (user_data));
	gtk_text_buffer_copy_clipboard (textbuffer,
					gtk_clipboard_get (GDK_NONE));
}


void
on_clear_activate (GtkMenuItem * menuitem, gpointer user_data)
{
	GtkTextBuffer *textbuffer = NULL;
	GtkTextIter start, end;

	g_assert (GTK_IS_TEXT_VIEW (user_data));

	textbuffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (user_data));
	gtk_text_buffer_get_bounds (textbuffer, &start, &end);
	gtk_text_buffer_delete (textbuffer, &start, &end);
}

void
on_font_activate (GtkMenuItem * menuitem, gpointer user_data)
{
	GtkWidget *FontDialog;

	FontDialog = create_easyreader_fontselectiondialog ();
	gtk_widget_show (FontDialog);
}

void
on_about_activate (GtkMenuItem * menuitem, gpointer user_data)
{
	GtkWidget *AboutDialog;

	AboutDialog = create_easyreader_about ();
	gtk_widget_show (AboutDialog);
}


void
on_open_toolbutton_clicked (GtkToolButton * toolbutton, gpointer user_data)
{
	GtkWidget *OpenDialog;

	OpenDialog = create_easyreader_fileopen ();
	gtk_widget_show (OpenDialog);
}


void
on_copy_toolbutton_clicked (GtkToolButton * toolbutton, gpointer user_data)
{
	GtkTextBuffer *textbuffer = NULL;

	g_assert (GTK_IS_TEXT_VIEW (user_data));
	textbuffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (user_data));
	gtk_text_buffer_copy_clipboard (textbuffer,
					gtk_clipboard_get (GDK_NONE));
}

void
on_clear_toolbutton_clicked (GtkToolButton * toolbutton, gpointer user_data)
{
	GtkTextBuffer *textbuffer = NULL;
	GtkTextIter start, end;

	g_assert (GTK_IS_TEXT_VIEW (user_data));

	textbuffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (user_data));
	gtk_text_buffer_get_bounds (textbuffer, &start, &end);
	gtk_text_buffer_delete (textbuffer, &start, &end);
}

void
on_font_toolbutton_clicked (GtkToolButton * toolbutton, gpointer user_data)
{
	GtkWidget *FontDialog;

	FontDialog = create_easyreader_fontselectiondialog ();
	gtk_widget_show (FontDialog);
}

void
on_quit_toolbutton_clicked (GtkToolButton * toolbutton, gpointer user_data)
{
	gtk_main_quit ();
}


void
on_about_toolbutton_clicked (GtkToolButton * toolbutton, gpointer user_data)
{
	GtkWidget *AboutDialog;

	AboutDialog = create_easyreader_about ();
	gtk_widget_show (AboutDialog);
}

void
on_Open_button_clicked (GtkButton * button, gpointer user_data)
{
	GtkTextIter iter, start, end;	// Итератор текстового буфера   
	gchar *local_codeset = NULL;
	gchar *read_buffer = NULL;
	gchar *ready_buffer = NULL;
	gchar *title_from_file_name = NULL;
	gint combo_box_text;
	FB2Content *fb;
	gchar *home;
	GtkWidget *nofiledialog;
	GtkWidget *convertdialog;
	GtkWidget *choosecodesetdialog;
	GError *err = NULL;

/* Очищаем окно просмотра текста. */
	gtk_text_buffer_get_bounds (buffer, &start, &end);
	gtk_text_buffer_delete (buffer, &start, &end);

	if (file_name != NULL)
		g_free (file_name);

	home = g_get_home_dir ();
	g_chdir (home);
	g_mkdir_with_parents (".easyreader", 0755);
	g_chdir (".easyreader");

	workfile = -1;
/* Грабим имя файла из диалога. */
	file_name =
		gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (user_data));
	if (!(file_name))
	{
		nofiledialog = gtk_message_dialog_new (NULL, 0,
						       GTK_MESSAGE_ERROR,
						       GTK_BUTTONS_CLOSE,
						       "Вы не выбрали файл!");
		gtk_window_set_modal (GTK_WINDOW (nofiledialog), TRUE);
		g_signal_connect (nofiledialog, "response",
				  G_CALLBACK (gtk_widget_destroy), NULL);
		gtk_widget_show (nofiledialog);
		return 0;
	}
/* Сообщаем имя файла. */
	g_message ("Selected file %s", file_name);
/* Открываем файл. */
	workfile = g_fopen (file_name, "rt");
	if (workfile == -1)
	{
		g_message ("Error open %s", file_name);
	}
/*Берем имя файла без полного пути 	к нему. */
	title_from_file_name = g_path_get_basename (file_name);
/* Меняем заголовок окна */
	gtk_window_set_title (GTK_WINDOW (easyreader_main_window),
			      title_from_file_name);
/* Берем полный путь к файлу. */
	path_to_file = g_path_get_dirname (file_name);
/* Устанавливаем текущую директорию рабочей. */
	gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (user_data),
					     path_to_file);
/* Устанавливаем итератор на начало текста. */
	gtk_text_buffer_get_start_iter (buffer, &iter);
/* Если открываем rtf, то подключаем парсер. */
	if (strstr (title_from_file_name, ".rtf"))
	{
		tempfile = g_fopen ("easyreader.tmp", "w");
		ConvertRTF (file_name);
		fclose (tempfile);
/* Читаем из файла, пишем в буфер. */
		g_file_get_contents ("easyreader.tmp", &read_buffer,
				     NULL, NULL);
	}
/* Аналогично fb2. */
	else if (strstr (title_from_file_name, ".fb2"))
	{
		fb = parseFile (file_name);
		tempfile = g_fopen ("easyreader.tmp", "w");
		fprintf (tempfile, fb->text);
		fclose (tempfile);
/* Читаем из файла, пишем в буфер. */
		g_file_get_contents ("easyreader.tmp", &read_buffer,
				     NULL, NULL);
		freeFB2 (fb);
	}
	else
/* Читаем из файла, пишем в буфер.*/
		g_file_get_contents (file_name, &read_buffer, NULL, NULL);
/* Определяем текущую локаль. */
	g_get_charset (&local_codeset);
	combo_box_text = gtk_combo_box_get_active (GTK_COMBO_BOX (combo_box));
	switch (combo_box_text)
	{
	case 0:
	{
		g_message ("Converting...");
/* Предупреждающий диалог. */
		convertdialog = gtk_message_dialog_new (NULL, 0,
							GTK_MESSAGE_INFO,
							GTK_BUTTONS_CLOSE,
							"Меняем кодировку текста,\nпожалуйста, подождите...");
		g_signal_connect (convertdialog, "response",
				  G_CALLBACK (gtk_widget_destroy), NULL);
		gtk_widget_show (convertdialog);
/* Меняем кодировку текста. */
		ready_buffer =
			g_convert (read_buffer, -1,
				   local_codeset, "UTF-8", NULL, NULL, &err);
		if (err)
		{
			gtk_widget_destroy (convertdialog);
			choosecodesetdialog = gtk_message_dialog_new (NULL, 0,
								      GTK_MESSAGE_ERROR,
								      GTK_BUTTONS_CLOSE,
								      "Выберите другую кодировку текста!");
			gtk_window_set_modal (GTK_WINDOW
					      (choosecodesetdialog), TRUE);
			g_signal_connect (choosecodesetdialog, "response",
					  G_CALLBACK (gtk_widget_destroy),
					  NULL);
			gtk_widget_show (choosecodesetdialog);
			return 0;
		}
/* Вставляем текст. */
		gtk_text_buffer_insert (buffer, &iter, ready_buffer, -1);
	}
		break;
	case 1:
	{
		g_message ("Converting...");
/* Предупреждающий диалог. */
		convertdialog = gtk_message_dialog_new (NULL, 0,
							GTK_MESSAGE_INFO,
							GTK_BUTTONS_CLOSE,
							"Меняем кодировку текста,\nпожалуйста, подождите...");
		g_signal_connect (convertdialog, "response",
				  G_CALLBACK (gtk_widget_destroy), NULL);
		gtk_widget_show (convertdialog);
/* Меняем кодировку текста. */
		ready_buffer =
			g_convert (read_buffer, -1,
				   local_codeset, "CP866", NULL, NULL, &err);
		if (err)
		{
			gtk_widget_destroy (convertdialog);
			choosecodesetdialog = gtk_message_dialog_new (NULL, 0,
								      GTK_MESSAGE_ERROR,
								      GTK_BUTTONS_CLOSE,
								      "Выберите другую кодировку текста!");
			gtk_window_set_modal (GTK_WINDOW
					      (choosecodesetdialog), TRUE);
			g_signal_connect (choosecodesetdialog, "response",
					  G_CALLBACK (gtk_widget_destroy),
					  NULL);
			gtk_widget_show (choosecodesetdialog);
			return 0;
		}
/* Вставляем текст. */
		gtk_text_buffer_insert (buffer, &iter, ready_buffer, -1);
	}
		break;
	case 2:
	{
		g_message ("Converting...");
/* Предупреждающий диалог. */
		convertdialog = gtk_message_dialog_new (NULL, 0,
							GTK_MESSAGE_INFO,
							GTK_BUTTONS_CLOSE,
							"Меняем кодировку текста,\nпожалуйста, подождите...");
		g_signal_connect (convertdialog, "response",
				  G_CALLBACK (gtk_widget_destroy), NULL);
		gtk_widget_show (convertdialog);
/* Меняем кодировку текста. */
		ready_buffer =
			g_convert (read_buffer, -1,
				   local_codeset, "CP1251", NULL, NULL, &err);
		if (err)
		{
			gtk_widget_destroy (convertdialog);
			choosecodesetdialog = gtk_message_dialog_new (NULL, 0,
								      GTK_MESSAGE_ERROR,
								      GTK_BUTTONS_CLOSE,
								      "Выберите другую кодировку текста!");
			gtk_window_set_modal (GTK_WINDOW
					      (choosecodesetdialog), TRUE);
			g_signal_connect (choosecodesetdialog, "response",
					  G_CALLBACK (gtk_widget_destroy),
					  NULL);
			gtk_widget_show (choosecodesetdialog);
			return 0;
		}
/* Вставляем текст. */
		gtk_text_buffer_insert (buffer, &iter, ready_buffer, -1);
	}
		break;
	case 3:
	{
		g_message ("Converting...");
/* Предупреждающий диалог. */
		convertdialog = gtk_message_dialog_new (NULL, 0,
							GTK_MESSAGE_INFO,
							GTK_BUTTONS_CLOSE,
							"Меняем кодировку текста,\nпожалуйста, подождите...");
		g_signal_connect (convertdialog, "response",
				  G_CALLBACK (gtk_widget_destroy), NULL);
		gtk_widget_show (convertdialog);
/* Меняем кодировку текста. */
		ready_buffer =
			g_convert (read_buffer, -1,
				   local_codeset, "IBM855", NULL, NULL, &err);
		if (err)
		{
			gtk_widget_destroy (convertdialog);
			choosecodesetdialog = gtk_message_dialog_new (NULL, 0,
								      GTK_MESSAGE_ERROR,
								      GTK_BUTTONS_CLOSE,
								      "Выберите другую кодировку текста!");
			gtk_window_set_modal (GTK_WINDOW
					      (choosecodesetdialog), TRUE);
			g_signal_connect (choosecodesetdialog, "response",
					  G_CALLBACK (gtk_widget_destroy),
					  NULL);
			gtk_widget_show (choosecodesetdialog);
			return 0;
		}
/* Вставляем текст. */
		gtk_text_buffer_insert (buffer, &iter, ready_buffer, -1);
	}
		break;
	case 4:
	{
		g_message ("Converting...");
/* Предупреждающий диалог. */
		convertdialog = gtk_message_dialog_new (NULL, 0,
							GTK_MESSAGE_INFO,
							GTK_BUTTONS_CLOSE,
							"Меняем кодировку текста,\nпожалуйста, подождите...");
		g_signal_connect (convertdialog, "response",
				  G_CALLBACK (gtk_widget_destroy), NULL);
		gtk_widget_show (convertdialog);
/* Меняем кодировку текста. */
		ready_buffer =
			g_convert (read_buffer, -1,
				   local_codeset, "ISO-8859-5", NULL,
				   NULL, &err);
		if (err)
		{
			gtk_widget_destroy (convertdialog);
			choosecodesetdialog = gtk_message_dialog_new (NULL, 0,
								      GTK_MESSAGE_ERROR,
								      GTK_BUTTONS_CLOSE,
								      "Выберите другую кодировку текста!");
			gtk_window_set_modal (GTK_WINDOW
					      (choosecodesetdialog), TRUE);
			g_signal_connect (choosecodesetdialog, "response",
					  G_CALLBACK (gtk_widget_destroy),
					  NULL);
			gtk_widget_show (choosecodesetdialog);
			return 0;
		}
/* Вставляем текст. */
		gtk_text_buffer_insert (buffer, &iter, ready_buffer, -1);
	}
		break;
	case 5:
	{
		g_message ("Converting...");
/* Предупреждающий диалог. */
		convertdialog = gtk_message_dialog_new (NULL, 0,
							GTK_MESSAGE_INFO,
							GTK_BUTTONS_CLOSE,
							"Меняем кодировку текста,\nпожалуйста, подождите...");
		g_signal_connect (convertdialog, "response",
				  G_CALLBACK (gtk_widget_destroy), NULL);
		gtk_widget_show (convertdialog);
/* Меняем кодировку текста. */
		ready_buffer =
			g_convert (read_buffer, -1,
				   local_codeset, "KOI8R", NULL, NULL, &err);
		if (err)
		{
			gtk_widget_destroy (convertdialog);
			choosecodesetdialog = gtk_message_dialog_new (NULL, 0,
								      GTK_MESSAGE_ERROR,
								      GTK_BUTTONS_CLOSE,
								      "Выберите другую кодировку текста!");
			gtk_window_set_modal (GTK_WINDOW
					      (choosecodesetdialog), TRUE);
			g_signal_connect (choosecodesetdialog, "response",
					  G_CALLBACK (gtk_widget_destroy),
					  NULL);
			gtk_widget_show (choosecodesetdialog);
			return 0;
		}
/* Вставляем текст. */
		gtk_text_buffer_insert (buffer, &iter, ready_buffer, -1);
	}
		break;
	default:
		break;
	}
/* Очищаем буфер текста */
	g_free (read_buffer);
	g_free (ready_buffer);
	g_remove ("easyreader_temp.tmp");
}

/* Взято из Leafpad */
void
set_text_font_by_name (GtkWidget * widget, gchar * fontname)
{
	PangoFontDescription *font_desc;

	font_desc = pango_font_description_from_string (fontname);
	gtk_widget_modify_font (widget, font_desc);
	pango_font_description_free (font_desc);
}

/* Взято из Leafpad */
gchar *
get_font_name_from_widget (GtkWidget * widget)	/* MUST BE FREED */
{
	GtkStyle *style;

	style = gtk_widget_get_style (widget);
	return pango_font_description_to_string (style->font_desc);
}

void
on_ok_button_clicked (GtkButton * button, gpointer user_data)
{
	gchar *current_fontname, *fontname;

	current_fontname = get_font_name_from_widget (main_textview);
	fontname =
		gtk_font_selection_dialog_get_font_name
		(GTK_FONT_SELECTION_DIALOG (user_data));
	if (fontname)
	{
		set_text_font_by_name (main_textview, fontname);
	}
	g_free (fontname);
	g_free (current_fontname);

}
